package com.uoko.common.collection;

import com.uoko.common.string.Strings;

import java.util.Collection;
import java.util.function.Function;


/**
 * <p>
 *
 * </p>
 *
 * @author chenyingchun
 * Email qiaohai@uoko.com
 * created by 2018/6/6 0006
 */
public class SplitMultMap<V> extends MultiMap<String, V> {

	/**
	 * key的分隔字符 例如:CKG/PEK/SSF。会作为三个key进行索引。
	 */
	private String splitString = "/";

	public SplitMultMap() {
		super();
	}

	public SplitMultMap(String splitString) {
		super();
		if (Strings.isNotBlank(splitString)) {
			this.splitString = splitString;
		}
	}

	/**
	 * 把字符串按照分隔符号进行分隔成字符数组。
	 * 
	 * @param sourceString
	 * @return
	 */
	private String[] getList(String sourceString) {
		if (Strings.isBlank(sourceString)) {
			return null;
		}
		return sourceString.split(splitString);
	}

	@Override
	public void put(String key, V value) {
		String[] stationList = getList(key);
		if (stationList != null) {
			for (String s : stationList) {
				super.put(s, value);
			}
		}
	}

	@Override
	public void remove(String key, V value) {
		String[] stationList = getList(key);
		if (stationList != null)
		{
			for (String s : stationList)
			{
				super.remove(s, value);

			}
		}
	}

	@Override
	public void putAll(String key, Collection<V> values) {
		String[] stationList = getList(key);
		if (stationList != null) {
			for (String s : stationList) {
				super.putAll(s, values);

			}
		}
	}

	@Override
	public void removeAll(String key) {
		String[] stationList = getList(key);
		if (stationList != null) {
			for (String s : stationList) {
				super.removeAll(s);
			}
		}
	}

	/**
	 * index,通用用于对集合建立索引;
	 * 
	 * @param list
	 * @param action
	 * @return
	 */
	public static <T> SplitMultMap<T> index(Collection<T> list, Function<T, String> action) {

		if (list == null || list.isEmpty()) {
			return null;
		}
		SplitMultMap<T> resMap = new SplitMultMap<>();
		list.forEach((value) -> {
			resMap.put(action.apply(value), value);
		});
		return resMap;
	}

}
